package com.gzhryc.shared_device.oem.h5.agent.mng.controllers.market.api;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.lang3.StringUtils;

import com.gzhryc.common.ClassTools;
import com.gzhryc.common.api.DefaultAPICodeConstants;
import com.gzhryc.common.exceptions.LogicException;
import com.gzhryc.common.logging.Logger;
import com.gzhryc.net_marketing.api.protocol.order.CreateSupplierGoodsOrderRequest;
import com.gzhryc.net_marketing.api.protocol.order.CreateSupplierGoodsOrderResponse;
import com.gzhryc.net_marketing.api.protocol.order.GetSupplierGoodsOrderRequest;
import com.gzhryc.net_marketing.api.protocol.order.GetSupplierGoodsOrderResponse;
import com.gzhryc.net_marketing.api.protocol.order.UpdateGoodsOrderAddressRequest;
import com.gzhryc.net_marketing.api.protocol.order.UpdateGoodsOrderAddressResponse;
import com.gzhryc.net_marketing.core.enums.EGoodsClassify;
import com.gzhryc.net_marketing.core.enums.EGoodsState;
import com.gzhryc.net_marketing.supplier.Supplier;
import com.gzhryc.net_marketing.supplier.SupplierManager;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoods;
import com.gzhryc.net_marketing.supplier.erp.dao.db.SupplierGoodsSpace;
import com.gzhryc.net_marketing.supplier.erp.services.SupplierGoodsService;
import com.gzhryc.net_marketing.supplier.erp.services.SupplierGoodsSpaceService;
import com.gzhryc.net_marketing.supplier.pay.dao.db.SupplierBusinessOrder;
import com.gzhryc.net_marketing.supplier.pay.services.SupplierBusinessOrderLogService;
import com.gzhryc.net_marketing.supplier.pay.services.SupplierBusinessOrderService;
import com.gzhryc.net_marketing.supplier.pay.services.dto.PayConfig;
import com.gzhryc.net_marketing.supplier.pay.services.dto.ReceiveAddress;
import com.gzhryc.servlet.WebUtils;
import com.gzhryc.servlet.annotation.Route;
import com.gzhryc.shared_device.base.enums.EOperatorType;
import com.gzhryc.shared_device.oem.h5.agent.mng.WebConstants;

public class SupplierBusinessOrderAPIController {

    static Logger log = Logger.getLogger(SupplierBusinessOrderAPIController.class);

    @Route(value = { "/supplier_api/v1/{supplierId}/goods/order/create.do" })
    public CreateSupplierGoodsOrderResponse createGoodsOrder(HttpServletRequest request){
        CreateSupplierGoodsOrderResponse apiResp = new CreateSupplierGoodsOrderResponse(DefaultAPICodeConstants.EXECUTE_ERROR,"处理失败");
        CreateSupplierGoodsOrderRequest apiReq = WebUtils.getJsonRequest(request,CreateSupplierGoodsOrderRequest.class);
        Long supplierId = WebUtils.getLong(request,"supplierId");
        if(apiReq != null && supplierId != null && apiReq.getBody().getProjectId() != null && StringUtils.isNotBlank(apiReq.getBody().getGoodsCode())
            && apiReq.getBody().getGoodsCount() != null) {
            if(SupplierManager.setCurrentSupplierId(supplierId)) {
                try {
                	Supplier supplier = SupplierManager.getSupplier();
                	if(supplier != null) {
	                    if(apiReq.getBody().getGoodsCount() < 1 || apiReq.getBody().getGoodsCount() > 9999){
	                        throw new LogicException("商品购买数量错误");
	                    }
	
	                    SupplierGoods goods = SupplierGoodsService.self().getByCode(apiReq.getBody().getGoodsCode());
	                    if(goods == null){
	                        throw new LogicException("商品不存在");
	                    }
	
	                    if(!EGoodsState.PutOnTheShelf.index().equals(goods.getState())){
	                        throw new LogicException(EGoodsState.note(goods.getState()));
	                    }
	
	                    if(EGoodsClassify.Entity.index().equals(goods.getClassify())){
	                        //检查收货地址
	                        if(StringUtils.isBlank(apiReq.getBody().getReceiveName()) || StringUtils.isBlank(apiReq.getBody().getReceivePhone())
	                                || StringUtils.isBlank(apiReq.getBody().getReceiveAddress())){
	                            apiResp.setMsg("收货地址信息不全");
	                            return apiResp;
	                        }
	                    }else {
	                        if(StringUtils.isBlank(apiReq.getBody().getReceivePhone())){
	                            apiResp.setMsg("请填写充值手机号");
	                            return apiResp;
	                        }
	                    }
	
	                    SupplierGoodsSpace goodsSpace = null;
	                    if(apiReq.getBody().getGoodsSpaceId() != null){
	                        goodsSpace = SupplierGoodsSpaceService.self().getByKeys(goods.getId(),apiReq.getBody().getGoodsSpaceId());
	                        if(goodsSpace == null){
	                            throw new LogicException("商品的规格不存在");
	                        }else if(!EGoodsState.PutOnTheShelf.index().equals(goodsSpace.getState())){
	                            throw new LogicException("商品规格：" + EGoodsState.note(goods.getState()));
	                        }
	                    }
	
	                    PayConfig payConfig = new PayConfig();
	                    payConfig.setProjectId(apiReq.getBody().getProjectId());
	                    payConfig.setProjectName(apiReq.getBody().getProjectName());
	                    payConfig.setProjectTradeNo(apiReq.getBody().getProjectTradeNo());
	                    payConfig.setGoodsCount(apiReq.getBody().getGoodsCount());
	                    payConfig.setLogisticsCompanyId(apiReq.getBody().getLogisticsCompanyId());
	
	                    ReceiveAddress receiveAddress = new ReceiveAddress();
	                    receiveAddress.setName(apiReq.getBody().getReceiveName());
	                    receiveAddress.setPhone(apiReq.getBody().getReceivePhone());
	                    receiveAddress.setProvince(apiReq.getBody().getReceiveProvince());
	                    receiveAddress.setAddress(apiReq.getBody().getReceiveAddress());
	
	                    SupplierBusinessOrder businessOrder = SupplierBusinessOrderService.self().buildBusinessOrder(supplier,goods,goodsSpace,receiveAddress,payConfig);
	                    if(businessOrder != null){
	                        apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
	                        apiResp.getBody().setTradeNo(businessOrder.getTradeNo());
	                        apiResp.getBody().setProjectTradeNo(businessOrder.getProjectTradeNo());
	                        apiResp.getBody().setGoodsMoney(businessOrder.getGoodsMoney());
	                        apiResp.getBody().setLogisticsMoney(businessOrder.getLogisticsMoney());
	                        apiResp.getBody().setMoney(businessOrder.getMoney());
	                        apiResp.getBody().setPayMoney(businessOrder.getPayMoney());
	                        apiResp.getBody().setLogisticsCompanyId(businessOrder.getLogisticsCompanyId());
	                        apiResp.getBody().setLogisticsCompany(businessOrder.getLogisticsCompany());
	                        apiResp.getBody().setState(businessOrder.getState());
	                        //TODO 需要重新整理
	                        SupplierBusinessOrderLogService.self().addCreateOrder(businessOrder.getTradeNo(), WebConstants.PROGRAM_TYPE
	                                , EOperatorType.Member.index(),businessOrder.getProjectName() + "("+businessOrder.getProjectId()+")");
	                    }
                	}
                }catch (LogicException e) {
                    apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,e.getMessage());
                }catch (Exception e) {
                    log.error(e.getMessage(), e);
                }finally{
                    SupplierManager.removeCurrentSupplierId();
                }
            }else{
                apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"供货商不存在");
            }
        }else{
            log.error("创建订单时参数错误，请求参数：{{0:json}}",apiReq);
            apiResp.setCode(DefaultAPICodeConstants.EXECUTE_ERROR,"参数错误");
        }
        return apiResp;
    }

    @Route(value = { "/supplier_api/v1/{supplierId}/goods/order/get.do" })
    public GetSupplierGoodsOrderResponse getGoodsOrder(HttpServletRequest request) {
        GetSupplierGoodsOrderResponse apiResp = new GetSupplierGoodsOrderResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "获取订单失败");
        GetSupplierGoodsOrderRequest apiReq = WebUtils.getJsonRequest(request, GetSupplierGoodsOrderRequest.class);
        Long supplierId = WebUtils.getLong(request, "supplierId");
        if (apiReq != null && supplierId != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo())) {
            if (SupplierManager.setCurrentSupplierId(supplierId)) {
                log.info("获取订单供应商{{0}}订单，请求：{{1:json}}",supplierId,apiReq.getBody());
                try {
                	Supplier supplier = SupplierManager.getSupplier();
                	if(supplier != null) {
	                	SupplierBusinessOrder businessOrder = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(apiReq.getBody().getTradeNo());
	                    if(businessOrder != null){
	                        apiResp.setCode(DefaultAPICodeConstants.SUCCESS,null);
	                        ClassTools.copyNotNull(apiResp.getBody(),businessOrder);
	                    }
                	}
                }catch (Exception e) {
                    log.error(e.getMessage(), e);
                }finally{
                    SupplierManager.removeCurrentSupplierId();
                }
            }
        }else{
            apiResp.setMsg("参数错误");
        }
        return apiResp;
    }

    @Route(value = { "/supplier_api/v1/{supplierId}/goods/order/address/update.do" })
    public UpdateGoodsOrderAddressResponse updateGoodsOrderAddress(HttpServletRequest request) {
        UpdateGoodsOrderAddressResponse apiResp = new UpdateGoodsOrderAddressResponse(DefaultAPICodeConstants.EXECUTE_ERROR, "获取订单失败");
        UpdateGoodsOrderAddressRequest apiReq = WebUtils.getJsonRequest(request, UpdateGoodsOrderAddressRequest.class);
        Long supplierId = WebUtils.getLong(request, "supplierId");
        if (apiReq != null && supplierId != null && StringUtils.isNotBlank(apiReq.getBody().getTradeNo())) {
            if (SupplierManager.setCurrentSupplierId(supplierId)) {
                try {
                	Supplier supplier = SupplierManager.getSupplier();
                	if(supplier != null) {
	                    SupplierBusinessOrder businessOrder = SupplierBusinessOrderService.self(supplier.getJdbcKey()).getByTradeNo(apiReq.getBody().getTradeNo());
	                    if(businessOrder != null){
	                        businessOrder.setReceiveName(apiReq.getBody().getReceiveName());
	                        businessOrder.setReceivePhone(apiReq.getBody().getReceivePhone());
	                        businessOrder.setReceiveProvince(apiReq.getBody().getReceiveProvince());
	                        businessOrder.setReceiveAddress(apiReq.getBody().getReceiveAddress());
	                        if(SupplierBusinessOrderService.self().updateReceiveAddress(businessOrder)) {
	                            apiResp.setCode(DefaultAPICodeConstants.SUCCESS, null);
	                        }
	                    }
                	}
                }catch (Exception e) {
                    log.error(e.getMessage(), e);
                }finally{
                    SupplierManager.removeCurrentSupplierId();
                }
            }
        }else{
            apiResp.setMsg("参数错误");
        }
        return apiResp;
    }
}
